package pers.liyan.shi.springboot.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket消息处理类
 *
 * @author shily
 * @date 2019/6/17 22:02
 */
@Deprecated
@Component
@ServerEndpoint("/websocket")
public class MyWebSocket {

    Logger logger = LoggerFactory.getLogger(MyWebSocket.class);

    /**
     * 在线人数
     */
    private static AtomicInteger onlineCount;

    /**
     * 用于存放客户端的WebSocket对象
     */
    private static CopyOnWriteArrayList<MyWebSocket> webSockets = new CopyOnWriteArrayList<>();

    /**
     * 与某个客户端建立连接时需要使用session发送数据
     */
    private Session session;

    /**
     * 建立连接时调用的方法
     *
     * @author shily
     * @date 2019/6/17 22:07
     */
    @OnOpen
    public void onOpen(Session session) {

        this.session = session;
        webSockets.add(this);
        onlineCount.incrementAndGet();
        logger.info("有新连接建立, 当前在线人数 " + onlineCount.get());
        try {
            sendMessage("你已成功建立连接");
        } catch (IOException e) {
            logger.warn(e.getMessage());
        }
    }


    /**
     * 连接关闭调用的方法
     *
     * @author shily
     * @date 2019/6/17 22:13
     */
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        onlineCount.decrementAndGet();
    }

    /**
     * 收到客户端发送的消息时调用
     *
     * @author shily
     * @date 2019/6/17 22:22
     */
    public void onMessage(String message, Session session) {

        logger.info("收到客户端的消息 " + message);
        //群发
        sendGroupMessage(message);

    }


    /**
     * 发生错误时调用
     *
     * @author shily
     * @date 2019/6/17 22:21
     */
    public void onError(Session session, Throwable throwable) {

        logger.warn("WebSocket发生错误");
        logger.warn(throwable.getMessage());

    }

    /**
     * 群发文本消息
     *
     * @param message 消息
     * @author shily
     * @date 2019/6/17 22:19
     */
    private void sendGroupMessage(String message) {
        for (MyWebSocket webSocket : webSockets) {
            try {
                webSocket.sendMessage(message);
            } catch (IOException e) {
                logger.warn(e.getMessage());
            }
        }
    }

    /**
     * 发送文本消息
     *
     * @param message 消息
     * @author shily
     * @date 2019/6/17 22:17
     */
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}
